package com.lo.common;

import org.springframework.stereotype.Component;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Component
public class FileExtract {

    public String fileExtractText(String filePath) throws Exception{
        String text;
        if(filePath.isEmpty()){
            return "";
        }
        if(filePath.toLowerCase().endsWith("doc")){
            InputStream file = new FileInputStream(new File(filePath));
            WordExtractor wordExtractor = new WordExtractor(file);
            text = wordExtractor.getText();
            file.close();
            wordExtractor.close();
        }
        else if(filePath.toLowerCase().endsWith("docx")){
            OPCPackage opcPackage = POIXMLDocument.openPackage(filePath);
            POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
            text = extractor.getText();
            opcPackage.close();
            extractor.close();
        }
        else if(filePath.toLowerCase().endsWith("pdf")){
            PDDocument pdDocument;
            InputStream file = new FileInputStream(new File(filePath));
            pdDocument = PDDocument.load(file);
            PDFTextStripper stripper = new PDFTextStripper();
            text = stripper.getText(pdDocument);
            file.close();
            pdDocument.close();
        }else {
            return "error file";
        }
        return text;
    }
}
